//
//  NSTimer+count.m
//  HKXProject
//
//  Created by wucha on 2017/9/26.
//  Copyright © 2017年 fc. All rights reserved.
//


#import "NSTimer+count.h"

@interface TimeInfo()
@property (nonatomic,strong) ChangeBlock changeBlock;
@property (nonatomic,strong) CompleteBlock completeBlock;
@property (nonatomic) int totalTime;
@property (nonatomic) int minTime;
+(TimeInfo*)initWithTimeInterval:(NSTimeInterval)ti time:(int)time changeBlock:(ChangeBlock)changeBlock completeBlock:(CompleteBlock)completeBlock;
-(void)counter:(NSTimer*)timer;

@end


@implementation TimeInfo

+(TimeInfo*)initWithTimeInterval:(NSTimeInterval)ti time:(int)time changeBlock:(ChangeBlock)changeBlock completeBlock:(CompleteBlock)completeBlock{
    TimeInfo *timeInfo = [[TimeInfo alloc] init];
    timeInfo.changeBlock = changeBlock;
    timeInfo.completeBlock = completeBlock;
    timeInfo.totalTime = time;
    timeInfo.minTime = ti;
    return timeInfo;
}

-(void)counter:(NSTimer*)timer{
    self.totalTime-=self.minTime;
    if (self.totalTime == 0) {
        if (self.completeBlock) {
            self.completeBlock();
        }
        [timer invalidate];
    }else{
        if (self.changeBlock) {
            self.changeBlock(self.totalTime);
        }
    }
    
}

@end

@implementation NSTimer (count)
+(NSTimer*)timerWithTimeInterval:(NSTimeInterval)ti time:(int)time changeBlock:(ChangeBlock)changeBlock completeBlock:(CompleteBlock)completeBlock{
    TimeInfo *timeInfo = [TimeInfo initWithTimeInterval:ti time:time changeBlock:changeBlock completeBlock:completeBlock];
    return [NSTimer scheduledTimerWithTimeInterval:1 target:timeInfo selector:@selector(counter:) userInfo:nil repeats:YES];
}
@end
